/* eslint-disable no-nested-ternary */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useState } from "react";
import { Link, useHistory } from "react-router-dom";
import {
    Filter,
    Responsive,
    List,
    TextInput,
    SelectInput,
    CardActions,
    CreateButton,
    Pagination,
    SimpleShowLayout,
    TextField,
    ReferenceField,
    useTranslate,
} from "react-admin";
import {
    Card,
    SwipeableDrawer,
    Dialog,
    DialogTitle,
    withStyles,
    AppBar,
    Toolbar,
    Typography,
    IconButton,
    Button,
    TextField as MuiTextField,
    Tabs,
    Tab,
} from "@material-ui/core";
import { ArrowBack } from "@material-ui/icons";

import { Transaction, RestAPI } from "rclink";
import ImageField from "./ImageField";
import { DateInput } from "../../raMuiDateInput";
import PasswordInputDialog from "./PasswordInputDialog";
import settings from "../../settings";
import { getKeypair } from "../../dataprovider/keypairsStore";
import StatusField from "./StatusFiled";

const CopRegFilter = props => (
    <Filter {...props}>
        <TextInput label="图片名称" source="imageName" alwaysOn />
        <TextInput label="图片描述" source="imageDesc" />
        <SelectInput label="登记状态" source="status" choices={[
            { id: "REQUESTED", name: "已请求" },
            { id: "REGISTERED", name: "已登记" },
            { id: "REJECTED", name: "已拒绝" },
        ]} />
        <DateInput
            label="操作时间"
            source="operationTime"
            parse={(v) => {
                const date = new Date(v);
                const dateStr = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
                console.log(dateStr);
                const dateTime = new Date(dateStr).getTime();
                return dateTime;
            }}
            options={{
                format: "yyyy/MM/dd",
                showTodayButton: true,
            }}
        />
    </Filter>
);

const PostActions = ({
    basePath,
    displayedFilters,
    filters,
    filterValues,
    resource,
    showFilter,
}) => (
    <div>
        <CardActions>
            {
                filters && React.cloneElement(filters, {
                    resource,
                    showFilter,
                    displayedFilters,
                    filterValues,
                    context: "button",
                })
            }
            <CreateButton basePath={basePath} />
        </CardActions>
    </div>
);

const ReviewForm = ({
    permissions, record, action, collectionData, copRegId, refresh, setRefresh,
}) => {
    if (permissions === "AUTHORITY_USER" && record.status === "REQUESTED") {
        let buttonLabel = action === "register" ? "registerButtonLabel" : "rejectButtonLabel";
        buttonLabel = useTranslate()(`resources.copRegs.fields.${buttonLabel}`);
        let inputLabel = action === "register" ? "registerNotes" : "rejectNotes";
        inputLabel = useTranslate()(`resources.copRegs.fields.${inputLabel}`);
        const [open, setOpen] = useState(false);
        const [notes, setNotes] = useState("");

        const handleOk = async (password) => {
            const chaincodeFunctionArgs = [JSON.stringify({
                hashArray: [record.image.hash],
                notes,
            })];
            const tx = new Transaction({
                type: "CHAINCODE_INVOKE",
                chaincodeName: settings.RepChain.default.chaincodeName,
                chaincodeVersion: settings.RepChain.default.chaincodeVersion,
                chaincodeInvokeParams: {
                    chaincodeFunction: `${action[0].toUpperCase()}${action.slice(1)}`,
                    chaincodeFunctionArgs,
                },
            });
            // eslint-disable-next-line no-undef
            const creditCode = localStorage.getItem("userId");
            const { prvKeyPEM, pubKeyPEM, certName } = await getKeypair(creditCode)
                .catch((e) => {
                    throw e;
                });
            let txSignedBuffer;
            try {
                txSignedBuffer = tx.sign({
                    prvKey: prvKeyPEM,
                    pubKey: pubKeyPEM,
                    alg: "ecdsa-with-SHA1",
                    pass: password,
                    creditCode,
                    certName,
                });
            } catch (e) {
                throw e;
            }

            const rest = new RestAPI(settings.RepChain.default.url_api);
            // eslint-disable-next-line no-undef
            const wsClient = new WebSocket(`${settings.Server.wsBaseUrl}/copRegs`, "echo-protocol");
            wsClient.onerror = ((ev) => {
                console.error("websocket error: ", ev);
            });
            wsClient.onmessage = (ev) => {
                const copReg = JSON.parse(ev.data);
                setOpen(false);
                collectionData[copRegId] = copReg;
                setRefresh(!refresh);
                console.log(copReg);
            };
            await rest.sendTransaction(txSignedBuffer)
                .then((r) => {
                    if (r.err) throw r.err;
                    console.log("TX send feedback:\n", JSON.stringify(r));
                })
                .catch((e) => {
                    throw e;
                });
        };

        return (
            <div>
                <MuiTextField
                    variant="filled"
                    margin="normal"
                    required
                    label={inputLabel}
                    style={{ display: "block" }}
                    onChange={e => setNotes(e.target.value)}
                />
                <Button color="primary" variant="contained"
                    onClick={() => setOpen(true)}
                    style={{ display: "block" }}
                >
                    {buttonLabel}
                </Button>
                <PasswordInputDialog
                    open={open}
                    setOpen={setOpen}
                    onPasswordOk={handleOk}
                />
            </div>
        );
    }
    return null;
};
const CopRegShowLayout = ({
    permissions, classes, data, copRegId, refresh, setRefresh, ...props
}) => {
    const history = useHistory();
    return (
        <SimpleShowLayout {...props} >
            <ImageField source="image.url" width="100%" height="auto" history={history} />
            <TextField source="copRegKey" className={classes.textField} />
            <StatusField source="status" />
            <TextField source="image.hash" className={classes.textField} />
            <TextField source="image.hashAlg" />
            <TextField source="image.name" className={classes.textField} />
            <TextField source="image.desc" className={classes.textField} />
            <ReferenceField label="申请登记交易" source="requestTxId" reference="Transaction" linkType="show">
                <TextField source="txid" className={classes.textField} />
            </ReferenceField>
            <TextField source="requestNotes" />
            {
                props.record && props.record.status === "REGISTERED"
                && <ReferenceField label="确认登记交易" source="registerTxId" reference="Transaction" linkType="show">
                    <TextField source="txid" className={classes.textField} />
                </ReferenceField>
            }
            {
                props.record && props.record.status === "REGISTERED"
                && <TextField source="registerNotes" />
            }
            <ReviewForm
                permissions={permissions}
                action="register"
                collectionData={data}
                copRegId={copRegId}
                refresh={refresh}
                setRefresh={setRefresh}
            />
            {
                props.record && props.record.status === "REJECTED"
                && <ReferenceField label="拒绝登记交易" source="rejectTxId" reference="Transaction" linkType="show">
                    <TextField source="txid" className={classes.textField} />
                </ReferenceField>
            }
            {
                props.record && props.record.status === "REJECTED"
                && <TextField source="rejectNotes" />
            }
            <ReviewForm
                permissions={permissions}
                action="reject"
                collectionData={data}
                copRegId={copRegId}
                setRefresh={setRefresh}
                refresh={refresh}
            />
        </SimpleShowLayout>
    );
};

const styles = {
    imageGrid: {
        margin: "1em",
    },
    card: {
        minHeight: 180,
        maxHeight: 280,
        maxWidth: 370,
        margin: "0.5em",
        display: "inline-block",
        verticalAlign: "top",
    },
    textField: {
        wordBreak: "break-all",
    },
    dialog: {
        width: 750,
        maxWidth: 800,
    },
    bar: {
        marginBottom: "1em",
        flexGrow: 1,
    },
    flex: {
        flexGrow: 1,
    },
    backButton: {
        marginLeft: "-0.6em",
        marginRight: "0.5em",
    },
};
const ImageGrid = withStyles(styles)(({
    ids, data, basePath, classes, ...props
}) => {
    const [open, setOpen] = useState(false);
    const [copRegId, setCopRegId] = useState("");

    const [refresh, setRefresh] = useState(false);


    return <div className={classes.imageGrid}>
        {
            ids.map(id => (
                // <Link key={id} to={{ pathname: `${basePath}/${id}/show` }}>
                <Link
                    key={id}
                    onClick={
                        () => {
                            setCopRegId(id);
                            setOpen(true);
                        }
                    }
                    to={{}}
                >
                    <Card
                        className={classes.card}
                    >
                        <Responsive
                            medium={
                                <ImageField
                                    record={data[id]}
                                    source="image.url"
                                    width={350}
                                    height={260}
                                />
                            }
                            small={
                                <ImageField
                                    record={data[id]}
                                    source="image.url"
                                    width={320}
                                    height={230}
                                />
                            }
                        />
                    </Card>
                </Link>
            ))
        }
        <Responsive
            small={
                <SwipeableDrawer
                    anchor="right"
                    open={open}
                    onClose={() => setOpen(false)}
                    // onKeyDown={() => setOpen(false)}
                    onOpen={() => { }}
                >
                    <div className={classes.bar}>
                        <AppBar color="secondary" position="static">
                            <Toolbar>
                                <IconButton className={classes.backButton} color="inherit" aria-label="Back"
                                    onClick={() => setOpen(false)}
                                >
                                    <ArrowBack />
                                </IconButton>
                                <Typography variant="title" color="inherit" className={classes.flex}>
                                    图片版权登记详情
                                </Typography>
                            </Toolbar>
                        </AppBar>
                    </div>
                    <CopRegShowLayout
                        record={data[copRegId]}
                        basePath={basePath}
                        classes={classes}
                        data={data}
                        copRegId={copRegId}
                        setRefresh={setRefresh}
                        refresh={refresh}
                        {...props}
                    />
                </SwipeableDrawer>
            }
            medium={
                <Dialog
                    open={open}
                    onClose={() => setOpen(false)}
                    // onKeyDown={() => setOpen(false)}
                    scroll="paper"
                    classes={{ paper: classes.dialog }}
                >
                    <DialogTitle>
                        <Typography variant="title" color="primary" className={classes.flex}>
                            图片版权登记详情
                        </Typography>
                    </DialogTitle>
                    <CopRegShowLayout
                        record={data[copRegId]}
                        basePath={basePath}
                        classes={classes}
                        data={data}
                        copRegId={copRegId}
                        setRefresh={setRefresh}
                        refresh={refresh}
                        {...props}
                    />
                </Dialog>}
        >
        </Responsive>
    </div>;
});

const CopRegList = ({ permissions, filter, ...props }) => (
    <List
        actions={<PostActions />}
        filters={<CopRegFilter />}
        filter={filter}
        sort={{ field: "updatedAt", order: "DESC" }}
        {...props}
        perPage={8}
        pagination={<Pagination rowsPerPageOptions={[8, 12, 25, 50]} />}
    >
        <ImageGrid permissions={permissions} />
    </List>
);

const CopRegListWithTabs = (props) => {
    const [value, setValue] = useState(0);
    return (
        <div>
            <Responsive
                medium={
                    <Tabs
                        value={value}
                        onChange={(e, newValue) => setValue(newValue)}
                        indicatorColor="primary"
                        textColor="primary"
                        style={{ marginBottom: 15 }}
                    >
                        <Tab label="公示图片" />
                        <Tab label="我的图片" />
                    </Tabs>
                }
                small={
                    <Tabs
                        value={value}
                        onChange={(e, newValue) => setValue(newValue)}
                        indicatorColor="primary"
                        textColor="primary"
                        variant="fullWidth"
                        style={{ marginBottom: 15 }}
                    >
                        <Tab label="公示图片" />
                        <Tab label="我的图片" />
                    </Tabs>
                }
            />

            {
                value === 0
                    ? <CopRegList {...props} />
                    // eslint-disable-next-line no-undef
                    : <CopRegList filter={{ ownerCreditCode: localStorage.getItem("userId") }} {...props} />
            }
        </div>
    );
};

export default CopRegListWithTabs;
